<template>
  <el-dialog
    class="add-parts-dialog"
    title="添加商品"
    :visible.sync="dialogVisible"
    width="70%"
  >
    <div class="add-parts-dialog-container">
      <div class="add-parts-dialog-header">
        <el-input
          class="add-parts-dialog-search-btn"
          placeholder="请输入商品名称/编号搜索"
          v-model="pageInfo.keyword"
        >
          <el-button
            type="primary"
            slot="append"
            @click="
              pageInfo.pageNum = 1;
              handleSearch();
            "
            >搜索</el-button
          >
        </el-input>
        <el-button @click="handleInit">重置</el-button>
      </div>

      <div class="add-parts-dialog-main">
        <div class="add-parts-dialog-left">
          <div class="add-parts-dialog-left-title">
            <div>
              <h3>请选择商品<span>仅可添加已上架的商品</span></h3>
            </div>
            <span>{{ `${selectedParts.length} / ${total}` }}</span>
          </div>

          <template v-if="tableData.length">
            <el-table
              ref="multipleTable"
              :data="tableData"
              stripe
              border
              row-key="id"
              style="width: 100%"
              @select="handleSelect"
              @select-all="handleSelectAll"
            >
              <el-table-column
                type="selection"
                :reserve-selection="true"
                width="40"
              >
              </el-table-column>
              <el-table-column prop="serialNumber" label="编号" width="140">
              </el-table-column>
              <el-table-column prop="title" label="名称"> </el-table-column>
              <el-table-column prop="repertoryCount" label="库存" width="88">
              </el-table-column>
              <el-table-column prop="salePrice" label="销售价" width="88">
              </el-table-column>
            </el-table>
            <el-pagination
              background
              layout="prev, pager, next"
              @current-change="handlePageChange"
              :total="total"
            >
            </el-pagination>
          </template>
          <template v-else>
            <div class="go_shop">
              去<a @click="goToShopCenter"><span>商城库</span></a
              >发布商品
            </div>
          </template>
        </div>

        <div class="add-parts-dialog-right">
          <div class="add-parts-dialog-right-title">已选择</div>
          <div class="add-parts-dialog-right-content">
            <div
              class="selected-parts-item"
              v-for="(item, index) in selectedParts"
              :key="index"
            >
              <span>{{ index + 1 }} - {{ item.title }}</span>
              <i class="el-icon-remove" @click="reduceParts(index)"></i>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div slot="footer">
      <el-button @click="closeSave()">关闭</el-button>
      <el-button
        type="primary"
        :disabled="pending"
        :loading="pending"
        @click="handleSave"
        >确定</el-button
      >
    </div>
  </el-dialog>
</template>

<script>
import _ from 'lodash';
import * as SettingApi from '@src/api/SettingApi.ts';
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'
import { openAccurateTab } from '@src/util/platform';
import { queryGoodsList } from '@src/api/PortalApi.ts';
import { getOssUrl } from '@src/util/assets'
const imgDefault = getOssUrl('/goodsDefault.png')

export default {
  name: 'mform-setting-add-parts-dialog',
  props: {
    value: {
      type: Array,
      default: () => [],
    },
    isOpenServiceMall: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      dialogVisible: false,
      pending: false,
      pageInfo: {
        pageNum: 1,
        pageSize: 10,
        keyword: '',
        putawayStatus: 1,
        // isShow: 1,
      },
      total: 0,
      selectedParts: [],
      tableData: [],
      otherPageSelected: [],
    };
  },
  methods: {
    async openDialog() {
      this.dialogVisible = true;

      this.selectedParts = _.cloneDeep(this.value);
      this.handleSearch();
    },
    async getPartsList() {
      const { code, result } = await SettingApi.getShopSparepartRepertory(
        this.pageInfo
      );

      if (code !== 0) return;

      const { list, total } = result.data;
      this.total = total;

      this.tableData = list.map(item => {
        const { id, image, imageList, name, serialNumber, salePrice } =
          item.baseSparepart;
        let imageUrl = imageList
          ? JSON.parse(imageList)[0]
          : image || imgDefault;

        return {
          imageUrl,
          id,
          title: name,
          serialNumber,
          salePrice,
          repertoryCount: item.repertoryCount,
        };
      });
    },
    async getGoodsList() {
      const { code, data } = await queryGoodsList(this.pageInfo);

      if (code !== '200') return;

      const { list, total } = data;
      this.total = total;

      this.tableData =
        list?.map(item => {
          const imageUrl = item.attachmentList?.length
            ? item.attachmentList[0]?.url
            : imgDefault;
          const price = item.priceType === 1 ? item.originPrice : item.price;

          return {
            imageUrl,
            id: item.id,
            title: item.commodityName,
            serialNumber: item.commodityCode,
            salePrice: price,
            repertoryCount: item.inventoryNumber,
          };
        }) || [];
    },
    renderPartsSelection(value = []) {
      this.$nextTick(() => {
        // 清空操作
        // this.selectedParts = [];
        // this.otherPageSelected = [];
        this.$refs.multipleTable.clearSelection();

        if (value.length === 0) return;
        value.forEach(row => {
          const item = this.tableData.find(v => v.id === row.id);
          if (item) this.$refs.multipleTable.toggleRowSelection(item);
        });
        this.selectedParts = value;
      });
    },
    goToShopCenter() {
      const type = this.isOpenServiceMall
        ? PageRoutesTypeEnum.PageLinkcGoodsList
        : PageRoutesTypeEnum.PagePartShopSetting;
      openAccurateTab({ type });
    },
    async handleSearch() {
      // 是否开启灰度控制
      if (this.isOpenServiceMall) {
        await this.getGoodsList();
      } else {
        await this.getPartsList();
      }

      // 重新渲染多选框状态
      this.renderPartsSelection(this.selectedParts);
    },
    handleInit() {
      this.pageInfo = {
        pageNum: 1,
        pageSize: 10,
        keyword: '',
        putawayStatus: 1,
      };

      this.handleSearch();
    },
    reduceParts(index) {
      const tableIndex = this.tableData.findIndex(
        item => item.id === this.selectedParts[index].id
      );

      // 在当前页面的备件直接切换selection状态，不在当前页的记录下来
      this.selectedParts.splice(index, 1);
      if (tableIndex > -1) {
        this.$nextTick(() => {
          this.$refs.multipleTable.toggleRowSelection(
            this.tableData[tableIndex]
          );
        });
      }
    },
    handleSelect(_, row) {
      const index = this.selectedParts.findIndex(f => f.id === row.id);
      if (index === -1) return this.selectedParts.push(row);

      this.selectedParts.splice(index, 1);
    },
    handleSelectAll(selection) {
      this.tableData.forEach(v => {
        const index = this.selectedParts.findIndex(f => f.id === v.id);
        if (selection.length === 0) {
          this.selectedParts.splice(index, 1);
        } else {
          if (index === -1) return this.selectedParts.push(v);
        }
      });
    },
    // handleSelectionChange(val) {
    //   if (this.otherPageSelected.length > 0) {
    //     this.otherPageSelected.forEach(item => val.splice(item, 1));
    //   }

    //   this.selectedParts = val;
    // },
    handlePageChange(value) {
      this.pageInfo.pageNum = value;
      this.handleSearch();
    },
    handleSave() {
      if (this.selectedParts.length > 4) {
        return this.$message({
          showClose: true,
          duration: 3000,
          message: '最多添加4个商品',
          type: 'error',
        });
      }
      this.$emit('input', this.selectedParts);

      this.dialogVisible = false;
    },
    closeSave() {
      this.dialogVisible = false;
    },
  },
  filters: {
    interceptString(value, len = 20, hasEllipsis = true) {
      if (!value) return;

      // 正则表达式匹配中文
      const regexp = /[^\x00-\xff]/g;
      // 当字符串字节长度小于指定的字节长度时
      if (value.replace(regexp, 'aa').length <= len) {
        return value;
      }

      // 假设指定长度内都是中文
      const m = Math.floor(len / 2);
      for (let i = m, j = value.length; i < j; i++) {
        // 当截取字符串字节长度满足指定的字节长度
        if (value.substring(0, i).replace(regexp, 'aa').length >= len) {
          return hasEllipsis
            ? `${value.substring(0, i)}...`
            : value.substring(0, i);
        }
      }
      return hasEllipsis ? `${value}...` : value;
    },
  },
};
</script>

<style lang="scss" scoped>
.add-parts-dialog-container {
  .add-parts-dialog-header {
    display: flex;

    .add-parts-dialog-search-btn {
      width: 364px;
      margin-right: 12px;
    }
  }

  .add-parts-dialog-main {
    display: flex;
    min-height: 378px;
    margin-top: 13px;

    .add-parts-dialog-left {
      width: 70%;
      margin-right: 32px;

      .add-parts-dialog-left-title {
        width: 100%;
        height: 32px;
        line-height: 32px;
        display: flex;
        justify-content: space-between;
        background: #f5f5f5;
        border-radius: 4px 4px 0px 0px;
        border: 1px solid #e8e8e8;
        font-family: PingFangSC-Medium, PingFang SC;
        padding: 0 16px;

        h3 {
          font-size: 14px;
          font-weight: 500;
          color: #333333;
          margin: 0 9px 0 0;
          span {
            margin-left: 10px;
          }
        }

        span {
          font-size: 12px;
          font-weight: 400;
          color: #8c8c8c;
        }
      }

      .el-pagination {
        margin-top: 18px;
        float: right;
      }

      .go_shop {
        line-height: 400px;
        text-align: center;
        a {
          margin: 0 10px;
          font-weight: bold;
          cursor: pointer;

          span {
            color: $color-primary-light-6;
          }
        }
      }
    }

    .add-parts-dialog-right {
      width: calc(30% - 32px);
      border-radius: 4px;
      border: 1px solid #e8e8e8;

      .add-parts-dialog-right-title {
        width: 100%;
        height: 32px;
        line-height: 32px;
        background: #f5f5f5;
        border-radius: 4px 4px 0px 0px;
        padding-left: 16px;
        font-size: 14px;
        font-family: PingFangSC-Medium, PingFang SC;
        font-weight: 500;
        color: #262626;
      }

      .add-parts-dialog-right-content {
        width: 100%;
        height: calc(100% - 32px);
        padding: 10px;
        display: flex;
        flex-direction: column;

        .selected-parts-item {
          width: 100%;
          height: 26px;
          display: flex;
          justify-content: space-between;
          align-items: center;
          cursor: pointer;
          margin-bottom: 6px;
          padding: 0 2px;

          span {
            @include text-ellipsis();
          }

          i {
            font-size: 14px;
            color: #ff4d4f;
            opacity: 0;
          }
        }

        .selected-parts-item:hover {
          background: #edf9f7;

          i {
            opacity: 1;
          }
        }
      }
    }
  }
}

.add-parts-dialog ::v-deep .el-dialog__body {
  padding: 18px;
}
::v-deep .el-input-group__append,
.el-input-group__prepend {
  border-radius: 0 4px 4px 0;
}
.add-parts-dialog-left ::v-deep .el-table {
  border-left: 1px solid #ebeef5;
}
</style>
